ext.define('extension.utils', function() {

var colors = [
    'blue',
    'orange',
    'red',
    'aqua',
    'maroon',
    'purple',
    'yellow',
    'green',
    'lime'
];

var colormap = [
    '2b75c7',
    'f97c00',
    'de3737',
    '009cc4',
    'd60095',
    '7030ab',
    'ffcf06',
    '4daa27',
    'a3e027'
];

var API = {
    clamp: function(x, min, max) {
        return Math.min(Math.max(x, min), max);
    },
    createWidget: function(cls, element, parent) {
        return Object.create(cls, {
            host: {value: element},
            shadow: {value: API.getShadowRoot(element)},
            parent: {value: parent}
        });
    },
    createShadowStyle: function(str) {
        return '@import "' + chrome.runtime.getURL(str) + '"';
    },
    getDocumentHeight: function() {
        var d = document.documentElement;
        return Math.max(d.clientHeight, d.scrollHeight, d.offsetHeight);
    },
    merge: function(a, b) {
        for (var k in b)
            a[k] = b[k];
        return a;
    },
    nop: function() {},
    findParentElement: function(nodes, element) {
        var elm, i = 0;
        while (elm = nodes[i++]) {
            if (elm === element || elm.contains(element))
                return elm;
        }
    },
    getShadowRoot: function(element) {
        if ('createShadowRoot' in element)
            return element.shadowRoot || element.createShadowRoot();
        return element['webkitShadowRoot'] || element.webkitCreateShadowRoot();
    },
    randomColor: function() {
        return colors[Math.floor(Math.random() * colors.length)];
    },
    extractColor: function(str) {
        var rx = new RegExp('(' + colors.join('|') + ')');
        var val = rx.exec(str);
        return val && val[0].trim();
    },
    mapColor: function(str) {
        var i = colors.indexOf(str);
        if (i != -1)
            return '#' + colormap[i];
    },
    colors: colors
};

return API;

});
